<?php
/**
 * This file is part of the wangningkai/olaindex.
 * (c) wangningkai <i@ningkai.wang>
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace App\Console\Commands;

use App\Service\Constants;
use Illuminate\Console\Command;
use App\Models\Account;
use Cache;

class UploadCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'upload {localfile} {remotefile} {account_id?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'upload file';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle(): void
    {
        //文档地址
        //https://docs.microsoft.com/en-us/graph/api/driveitem-createuploadsession?view=graph-rest-1.0#upload-bytes-to-the-upload-session


        $localfile =  $this->argument('localfile');
        $remotefile = $this->argument('remotefile');
        $_path = dirname($remotefile);//远程路径
        $_file = basename($remotefile);//远程文件名


        $account_id = $this->argument('account_id') ? $this->argument('account_id') : setting('primary_account', 0);
        $account = Account::find($account_id);
        if (!$account) {
//            return $this->fail('未知账号');
        }

        $service = $account->getOneDriveService();

        $resp = $service->createUploadSession($_path, $_file);
        if(empty($resp['uploadUrl'])){
            var_dump($resp);
            die;
        }

        $uploadUrl = $resp['uploadUrl'];
        $length = 5000000;//每次上传5M
        $start = 0;
        $filesize = _filesize($localfile);
        $contentLength = $filesize > $length ? $length : $filesize;
        $content = get_file_content($localfile, $start, $contentLength);
        $end = $start+$contentLength-1;
        //开始上传
        echo "开始上传：\n";
        echo "内容区块：{$start} - {$end}\n";
        $data = [];
        $data = $service->resumableUpload($uploadUrl, $start, $end, $contentLength, $filesize, $content);
        while (empty($data['file'])){
            sleep(0.5);
            $nextExpectedRanges = explode('-',$data['nextExpectedRanges'][0]);
            $start_index= $nextExpectedRanges[0];
            $end_index = $nextExpectedRanges[1];

            $start = $nextExpectedRanges[0];
            $contentLength = $start+$length-1 > $filesize-1 ? $end_index-$start_index+1 : $length;
            $end = $start + $contentLength - 1;
            $content = get_file_content($localfile, $start, $contentLength);
            echo "内容区块：{$start} - {$end}\n";

            $data = $service->resumableUpload($uploadUrl, $start, $end, $contentLength, $filesize, $content);

        }

        echo "上传成功！\n";

        Cache::flush();

    }


}

